<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Http\Services\Manage\ExportService;
use App\Models\LouAddress;
use App\Models\OrderAddress;
use App\Models\Supplier;
use App\Repositories\Manage\OrderRepository as ManageOrderRepository;
use App\Repositories\Manage\PrinterRepository as ManagePrinterRepository;
use App\Repositories\Manage\StallRepository;
use App\Repositories\OrderRepository;
use App\Repositories\PrinterRepository;

class OrderController extends ManageBaseController
{

    private $orderRepo = NULL, $printerRepo = NULL;

    public function __construct(
        ManageOrderRepository   $orderRepo,
        ManagePrinterRepository $printerRepo,

    )
    {
        parent::__construct();
        $this->orderRepo = $orderRepo;
        $this->printerRepo = $printerRepo;
    }

    public function index()
    {
        $filter = $this->_filter();
        $extra_conditions = [];
        if (isset($filter['between'])) {
            $extra_conditions['between'] = $filter['between'];
            unset($filter['between']);
        }

        if (!checkIsSuper(UID)) { //非系统管理员
            empty($filter['shop_id']) && $filter['shop_id'] = -1;
        }

        $res = $this->orderRepo->getList($filter, $this->pageNum, $this->pageSize, $extra_conditions);
        return retSuc($res);
    }

    /**
     * 更新备注
     * @param null $id
     */
    public function update_note($id = null)
    {
        if (!intval($id)) {
            return retFail("参数错误");
        }

        $order = $this->orderRepo->getOne($id);
        if (empty($order))
            return retFail("订单不存在");

        $params = request()->only(["note"]);
        $this->orderRepo->saveOrUpdate(['remark' => trim($params['note']) ?? ""], $id);

        return retSuc([], "更新成功");
    }

    public function detail($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");
        $res = $this->orderRepo->getOne($id);
        //        添加分账账户
        try {
            /*

            $query = (new WechatRepository())->queryProfile("4200002182202406236808274826", "2406231521293346409856");
            $rs = (new WechatRepository())->addProfileShare("1282617501", "南京博盛蓝睿网络科技有限公司");
            $transaction_id = $res['transaction_id'];
            $out_trade_no = date('ymdHis') . GenSecret(10, 1);
            $receivers = [
                [
                    "type" => "MERCHANT_ID",
                    "account" => "1282617501",
                    "amount" => intval($res['total_price'] * 0.3 * 100, 0),
                    "description" => "分润",
                ],
            ];
            $rs = (new WechatRepository())->doProfileShare($transaction_id, $out_trade_no, $receivers);
            dd($rs, $receivers);

            // $rs = (new WechatRepository())->addProfileShare("1666223810", "华公管商业");
            dd($rs);*/
        } catch (\Exception $e) {
            return retFail($e->getMessage());
        }

        return retSuc($res);
    }

    /**
     * 订单状态统计
     */
    public function stat_status()
    {
        $filter = $this->_filter();
        $statusList = order_filter_status();
        $statList = [];
        $sstatus = intval(request()->get("sstatus", 0));

        $condition = [];
        if ($filter['between']) {
            $condition['between'] = $filter['between'];
            unset($filter['between']);
        }

        foreach ($statusList as $k => $status) {

            if ($sstatus) {
                if ($k == $sstatus) {
                    $amount = $this->orderRepo->getStat($filter, $condition);
                } else {
                    $amount = 0;
                }
            } else {
                if ($filter['delivery_status'])
                    unset($filter['delivery_status']);

                if ($filter['deliver_status'])
                    unset($filter['deliver_status']);

                $s_filter = orderStatusMapping($k);
                $filter = array_merge($filter, $s_filter);
                $amount = $this->orderRepo->getStat($filter, $condition);
            }

            $statList[] = [
                'amount' => $amount,
                "status" => $k,
                "title" => $status
            ];
        }

        return retSuc($statList);
    }

    public function delete($id)
    {
        $ids = intval($id);

        if (empty($ids)) {
            return retFail("参数错误");
        }

        return $this->orderRepo->batchDelete($ids);
    }

    /**
     * 打印统计数据
     */
    public function printer_stat()
    {
        $filter = $this->_filter();
        if (!empty($filter['ids']) && count($filter['ids']) == 1) {
            $shop_id = (new OrderRepository())->getShopIdById($filter['ids'][0]);
        } else {
            $shop_id = intval($filter['shop_id']);
        }

        if (!$shop_id)
            return retFail("请选择店铺打印");
        $printers = (new PrinterRepository())->getOptions($shop_id, $filter['printer_type'] == 'label' ? 2 : 1);

        if (!isset($printers)) {
            return retFail("当前店铺没有打印机");
        }
        $stallList = [];
        //打印机
        if ($filter['printer_type'] == 'stall') {
            $data = $this->orderRepo->getOrderStallStat($filter);
            $total_product = array_sum(get_column($data, 'amount'));
        } else {
            $data = $this->orderRepo->getOrderStat($filter);
            $total_product = array_sum(get_column($data, 'product_amount'));
            $total_order = array_sum(get_column($data, 'order_amount'));
        }

        if ($filter['printer_type'] == 'label') {
            $stallList = (new StallRepository())->getOptions($shop_id);
        }

        return retSuc([
            'items' => $data,
            'printerList' => $printers,
            'stallList' => $stallList, //店铺对应的档口
            'total_product' => $total_product,
            'total_order' => $total_order,
        ]);
    }

    /**
     * 订单接单
     */
    public function accept()
    {
        $filter = $this->_filter();
        $filter['sstatus'] = request()->get("sstatus");

        if (($filter['status'] ?? 0) != 10 || !in_array($filter['delivery_status'] ?? 0, [0, 10])) {
            return retFail("参数错误");
        }

        return $this->orderRepo->acceptList($filter, UID);
    }

    /***
     * 退款
     * @param null $out_trade_no
     */
    public function refund($out_trade_no = null)
    {
        $params = request()->all();
        return $this->orderRepo->cancelOrder($out_trade_no, $params);
    }

    /**
     * 打印品单
     */
    public function printer_label()
    {
        $printer_id = intval(request()->post("printer_id"));
        if (!$printer_id)
            return retFail("请选择打印机");

        $printer = $this->printerRepo->getOne($printer_id);
        if (empty($printer))
            return retFail("打印机不存在");

        if ($printer['type'] != 2) {
            return retFail("请选择品单打印机");
        }
    }

    /**
     * 打印订单
     */
    public function printer()
    {
        $filter = $this->_filter();
        $printer_type = $filter['printer_type'];
        $printer_id = intval($filter['printer_id'] ?? 0);

        if ($printer_type == 'label') { //标签打印
            return (new  PrinterRepository())->printerLabel($filter, $printer_id, 1);
        } else if ($printer_type == 'order') { //打印订单
            return (new  OrderRepository())->printerOrder($filter, $printer_id, 1);
        } else if ($printer_type == 'stall') { //档口
            return (new  OrderRepository())->printerStall($filter, $printer_id, 1);
        } else if ($printer_type == 'keshi') { //科室  ToDo : 待处理
            return $this->orderRepo->getKsStat($filter, $printer_id);
        } else {
            return retFail("打印类型不存在");
        }

    }

    /**
     * 打印任务
     */
    public function task()
    {
        $filter = [];
        $res = $this->printerRepo->getTasks($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    private function _filter()
    {
        $params = request()->all();
        $filter['is_delete'] = 2;

        if (!empty($params['title'])) {
            $filter['title'] = array('like', '%' . $this->title . '%');
        }

//        打印类型
        !empty($params['printerType']) && $filter['printer_type'] = trim($params['printerType']);
        !empty($params['printer_id']) && $filter['printer_id'] = intval($params['printer_id']);

        if (intval($params['uid'])) {
            $filter['uid'] = $params['uid'];
        }

        if (!empty($params['pay_time'])) {
            $params['pay_time'][0] = strtotime($params['pay_time'][0]);
            $params['pay_time'][1] = strtotime($params['pay_time'][1]);
            $filter['between']['o.create_time'] = $params['pay_time'];
        }

        if (!empty($params['end_time'][1])) {
            $filter['end_time'] = $params['pay_time'][1];
        }

        $sstatus = intval($params['sstatus']);
        $s_filter = orderStatusMapping($sstatus);
        settype($filter, "array");
        $filter = array_merge($filter, $s_filter);
        if(intval($params['stype'] ?? 0) > 0)
            $filter['stype'] = $params['stype'] ?? 0;

        if (!empty($params['sout_trade_no'])) {
            $filter['out_trade_no'] = trim($params['sout_trade_no']);
        }

        if (!empty($params['order_source'])) {
            $filter['order_source'] = intval($params['order_source']);
        }

        if (intval($params['smenu_id'])) {
            $filter["menu_id"] = intval($params['smenu_id']);
        }

        if (!empty($params['stall_id'])) {
            $filter['stall_id'] = $params['stall_id'];
        }

        if (!checkIsSuper(UID)) { //非系统管理员
            $filter['shop_id'] = intval(getUserRelateShopId(UID));
        } else {
            if (intval($params['shop_id'])) {
                $filter["shop_id"] = intval($params['shop_id']);
            }
        }
        $sprovince_id = intval($params['sprovince_id']);
        $scity_id = intval($params['scity_id']);
        if ($sprovince_id) {
            if (!empty($scity_id)) {
                $oa_filter['city_id'] = $scity_id;
            }
            $oa_filter['province_id'] = $sprovince_id;
            $filter['ids'] = OrderAddress::query()->where($oa_filter)->pluck("order_id")->toArray();
        }

        $smin_menu_id = intval($params['start_callNo']);
        $smax_menu_id = intval($params['end_callNo']);
        if ($smin_menu_id) {
            $filter['start_callNo'] = $smin_menu_id;
        }
        if ($smax_menu_id) {
            $filter['end_callNo'] = $smax_menu_id;
        }

        $ids = $params["ids"] ?? "";
        if ($ids) {
            if (is_array($ids)) {
                $filter['ids'] = $ids;
            } else {
                $filter['ids'] = array_filter(explode("-", $ids));
            }
        }

        if (!empty($params['smobile'])) {
            $filter['ids'] = OrderAddress::query()->where("phone", "like", "%" . $params['smobile'] . "%")->pluck("order_id")->toArray();
        }
        intval($params['deliver_time']) && $filter['deliver_time'] = $params['deliver_time'];

        if ($filter["shop_id"] > 0)
            $filter['shop_type'] = Supplier::query()->where("id", $filter['shop_id'])->value("type");

        return $filter;
    }

    /**
     * 订单初始化条件
     */
    public function init_filter()
    {
        $s_filter['status'] = 1;
        if (!checkIsSuper(UID)) { //非系统管理员
            $s_filter['id'] = intval(getUserRelateShopId(UID));
        }
        $shopList = Supplier::query()->where($s_filter)->orderBy("sort", "asc")->get(['id', 'title', 'type']);

        $level1 = LouAddress::query()->where(['level' => 1, 'status' => 1])->get(["id", "title"])->toArray();
        $level1 = ass_column($level1, 'id');
        foreach ($level1 as $k => &$v) {
            if (intval($v['title'])) {
                $v['title'] .= '号楼';
            }
            $v['_child'] = LouAddress::query()->where(['level' => 2, 'status' => 1, 'pid' => $v['id']])->get(["id", "title"]);
        }

        return retSuc([
            'shopList' => $shopList,
            'areaList' => $level1,
            'deliverTimeList' => deliver_timeList()
        ]);

    }

    /**
     * 导出订单
     */
    public function export_order()
    {
        ini_set('memory_limit', '10240M');
        set_time_limit(0);

        $filter = $this->_filter();
        $extra_conditions = [];
        if (isset($filter['between'])) {
            $extra_conditions['between'] = $filter['between'];
            unset($filter['between']);
        }
        if (!checkIsSuper(UID)) { //非系统管理员
            empty($filter['shop_id']) && $filter['shop_id'] = -1;
        }

        $orders = $this->orderRepo->getOrderIdsByFilter($filter, $extra_conditions);
        // 导出excel
        $res = [];
        foreach ($orders as $k => $v) {
            $p_str = [];
            foreach ($v['products'] as $pk => $p) {
                if ($p['type'] == 2) {//多规格
                    $p_str[] = $p['title'] . ($p['sku_txt'] ? ('(' . $p['sku_txt'] . ')') : '') . ' x' . $p['amount'];
                } else if ($p['type'] == 1) { //套餐
                    $skus = [];
                    foreach ($p['skus'] as $sk => $sv) {
                        $skus[] = $sv['spec_item_title'] . 'x' . $sv['amount'];
                    }
                    $p_str[] = $p['title'] . ('(' . implode(',', $skus) . ')') . ' x' . $p['amount'];
                } else {
                    $p_str[] = $p['title'] . ' x' . $p['amount'];
                }
            }

            $d['out_trade_no'] = $v['out_trade_no'] . " ";
            $d['mobile'] = $v['phone'] . " ";
            $d['create_time'] = $v['create_time'];
            $d['shop_title'] = $v['shop_title'];
            $d['menu_date'] = $v['delivery_date'];
            $d['menu_title'] = $v['menu_title'] ?? "";
            $d['deliver_time'] = $v['deliver_time'] ?? " "; //送达时间
            $d['current_status'] = order_filter_status($v['current_status']);
            $d['products'] = implode(", ", $p_str);
            $d['skus'] = "";
            $d['amount'] = $v['amount'];
            $d['total_price'] = $v['total_price'];
            $d['bag_price'] = $v['bag_price'];
            $d['express_price'] = $v['express_price'];
            $d['pay_time'] = date("Y-m-d H:i:s", $v['pay_time']);

            $d['refund_time'] = $v['refund_time'] ?? "";
            $d['refund_fee'] = $v['refund_price'];
            $d['remark'] = trim($v['remark'] ?? "");
            $d['address'] = $v['province_title'] . '' .
                $v['city_title'] . $v['region_title'] . '' .
                $v['district_title'] .
                $v['address'] . ' ' .
                $v['consignee'];

            $res[] = $d;
        }

        $keys['out_trade_no'] = '订单号';
        $keys['phone'] = '手机号';
        $keys['create_time'] = '下单时间';
//        $keys['shop_type_title'] = '店铺类型';
        $keys['shop_title'] = '店铺';
        $keys['menu_date'] = '菜单时间';
        $keys['menu_title'] = '菜单餐段';

        $keys['deliver_time'] = '送达时间';
        $keys['current_status'] = '订单状态';
        $keys['products'] = '商品名称';
        $keys['skus'] = '规格/套餐';

        $keys['amount'] = '订单数量';
        $keys['total_price'] = '总金额';
        $keys['bag_price'] = '打包费';
        $keys['express_price'] = '配送费';
        $keys['pay_time'] = '支付时间';

        $keys['refund_time'] = '退款时间';
        $keys['refund_fee'] = '退款金额';
        $keys['remark'] = '客服备注';
        $keys['address'] = "收货信息";
        $keys['reason'] = "取消原因";

        $data = array_merge(array($keys), $res);
        return (new  ExportService())->download($res, $keys, "order");
    }

    /**
     * 导出档口
     */
    public function export_stall()
    {

    }


}
